package com.bsoft.gol.hcs.specialist.dao;

import ctd.persistence.annotation.DAOMethod;
import ctd.persistence.annotation.DAOParam;
import ctd.persistence.support.hibernate.HibernateSupportDelegateDAO;
import ctd.persistence.support.hibernate.template.AbstractHibernateStatelessResultAction;
import ctd.persistence.support.hibernate.template.HibernateSessionTemplate;
import ctd.persistence.support.hibernate.template.HibernateStatelessResultAction;
import ctd.util.converter.ConversionUtils;
import com.bsoft.gol.hcs.enumcase.FollowTypeEnum;
import org.hibernate.Query;
import org.hibernate.StatelessSession;
import org.hibernate.criterion.CriteriaSpecification;
import com.bsoft.gol.hcs.specialist.bean.request.GroupChronicRecordQo;
import com.bsoft.gol.hcs.specialist.bean.response.FactorData;
import com.bsoft.gol.hcs.specialist.bean.response.GroupStagesListResponse;
import com.bsoft.gol.hcs.specialist.bean.response.GroupStagesResponse;
import com.bsoft.gol.hcs.specialist.entity.FusGroupChronicRecordStagesProperty;
import com.bsoft.gol.hcs.utils.CommonUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 入组记录分期属性dao
 *
 * @author lanyu
 * @date 2021年09月29日 16:04
 */
public abstract class GroupRecordStagesPropertyDAO extends HibernateSupportDelegateDAO<FusGroupChronicRecordStagesProperty> {

    /**
     * 根据病种id和分期属性id获取入组记录分期信息
     *
     * @param diseaseTypeId
     * @return
     */
    @DAOMethod(sql = " from FusGroupChronicRecordStagesProperty where diseaseTypeId =:diseaseTypeId and stagesId =:stagesId order by createTime")
    public abstract List<FusGroupChronicRecordStagesProperty> queryGroupRecordStagesByDiseaseTypeId(@DAOParam("diseaseTypeId") Long diseaseTypeId, @DAOParam("stagesId") Long stagesId);
    /**
     * 根据病种id和分期属性id获取入组记录分期数量
     *
     * @param diseaseTypeId
     * @return
     */
    @DAOMethod(sql = " select count(1) from FusGroupChronicRecordStagesProperty where diseaseTypeId =:diseaseTypeId and stagesId =:stagesId order by createTime")
    public abstract Long getCountGroupRecordStagesByStagesId(@DAOParam("diseaseTypeId") Long diseaseTypeId, @DAOParam("stagesId") Long stagesId);

    /**
     * 根据病种id和入组记录id获取分期信息
     * @param diseaseTypeId
     * @param teamChronicGroupId
     * @return
     */
    @DAOMethod(sql = " from FusGroupChronicRecordStagesProperty where diseaseTypeId =:diseaseTypeId and teamChronicGroupId =:teamChronicGroupId order by stagesTime")
    public abstract List<FusGroupChronicRecordStagesProperty> queryGroupRecordStagesList(@DAOParam("diseaseTypeId") Long diseaseTypeId,@DAOParam("teamChronicGroupId") Long teamChronicGroupId);

    /**
     * 删除分期
     * @param stagesRecordId
     */
    @DAOMethod(sql =" delete from FusGroupChronicRecordStagesProperty where stagesRecordId=:stagesRecordId")
    public abstract void deleteStagesByStagesId(@DAOParam("stagesRecordId") Long stagesRecordId);
    /**
     *
     * 根据病种id获取分期
     * @param qo
     * @return
     */
    public List<GroupStagesResponse> queryFirstGroupStagesList(GroupChronicRecordQo qo) {
        HibernateStatelessResultAction<List<GroupStagesResponse>> action = new AbstractHibernateStatelessResultAction<List<GroupStagesResponse>>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                StringBuilder sqlBuilder = new StringBuilder();
                sqlBuilder.append("SELECT " +
                        " f.stages_record_id AS stagesRecordId, " +
                        " f.stages_id AS stagesId, " +
                        " f.stages_name AS stagesName, " +
                        " fs.periodViewDispFlag " +
                        "FROM " +
                        " fus_group_chronic_record_stages_property f " +
                        " INNER JOIN fus_disease_species_record fs ON f.disease_type_id = fs.disease_type_id  " +
                        " AND ISNULL( f.parent_id )  " +
                        " AND f.disease_type_id =:diseaseTypeId ");
                sqlBuilder.append(" and f.create_time >=:beginTime and f.create_time <=:endTime order by f.create_time ");
                Query query = ss.createSQLQuery(sqlBuilder.toString());
                query.setParameter("diseaseTypeId", qo.getDiseaseTypeId());
                if (CommonUtils.isNotEmpty(qo.getBeginTime())){
                    query.setParameter("beginTime", qo.getBeginTime()+" 00:00:00");
                }
                if (CommonUtils.isNotEmpty(qo.getBeginTime())){
                    query.setParameter("endTime", qo.getEndTime()+" 23:59:59");
                }
                query.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<Map> list = query.list();
                List<GroupStagesResponse> voList = new ArrayList<>();
                if (CommonUtils.isNotEmpty(list)) {
                    for (Map map : list) {
                        voList.add(ConversionUtils.convert(map, GroupStagesResponse.class));
                    }
                } else {
                    voList = new ArrayList<>();
                }
                setResult(voList);
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    /**
     *
     * 根据病种id获取分期
     * @param qo
     * @return
     */
    public List<GroupStagesListResponse> querySecondGroupStagesList(GroupChronicRecordQo qo) {
        HibernateStatelessResultAction<List<GroupStagesListResponse>> action = new AbstractHibernateStatelessResultAction<List<GroupStagesListResponse>>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                StringBuilder sqlBuilder = new StringBuilder();
                sqlBuilder.append(" SELECT " +
                        " f.stages_record_id AS stagesRecordId, " +
                        " f.stages_id AS stagesId, " +
                        " f.stages_name AS stageName, " +
                        " f.stages_time AS stagesTime, " +
                        " f.stages_abbreviation AS stagesAbbreviation, " +
                        " f.stages_code AS stagesCode, " +
                        " f.parent_id AS parentId, " +
                        " f.create_time AS createTime, " +
                        " f.create_user_id AS createUserId " +
                        "FROM " +
                        " fus_group_chronic_record_stages_property f left join fus_disease_species_record fd on f.disease_type_id = fd.disease_type_id " +
                        " where  " +
                        " f.disease_type_id =:diseaseTypeId ");
                sqlBuilder.append(" and f.create_time>=:beginTime and f.create_time<=:endTime and fd.periodViewDispFlag = 1 order by f.create_time ");
                Query query = ss.createSQLQuery(sqlBuilder.toString());
                query.setParameter("diseaseTypeId", qo.getDiseaseTypeId());
//                query.setParameter("stagesId",stagesId);
                if (CommonUtils.isNotEmpty(qo.getBeginTime())){
                    query.setParameter("beginTime", qo.getBeginTime()+" 00:00:00");
                }
                if (CommonUtils.isNotEmpty(qo.getBeginTime())){
                    query.setParameter("endTime", qo.getEndTime()+" 23:59:59");
                }
                query.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<Map> list = query.list();
                List<GroupStagesListResponse> voList = new ArrayList<>();
                if (CommonUtils.isNotEmpty(list)) {
                    for (Map map : list) {
                        voList.add(ConversionUtils.convert(map, GroupStagesListResponse.class));
                    }
                } else {
                    voList = new ArrayList<>();
                }
                setResult(voList);
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    /**
     * @description:
     * @param: factorIdList 诊断编码集合
     * @param: diagnosisTime
     * @param: diagnosisServiceType 业务诊断类型：1入院诊断、2出院诊断、3门诊诊断、5其他诊断
     * @param: patientIdList
     * @return: java.util.List<specialist.bean.response.FactorData>
     */

    /**
     * @description: 根据专病分期编码、开始时间、结束时间、病人id集合查询诊断记录集合
     * @param: factorIdList 专病分期编码集合
     * @param: startTime 专病分期修改开始时间
     * @param: endTime 专病分期修改结束时间
     * @param: patientIdList 病人id集合
     * @return: java.util.List<specialist.bean.response.FactorData>
     */
    public List<FactorData> executeFactorForDiseasePeriod(List<String> factorIdList, Date startTime, Date endTime, List<String> patientIdList,Byte isLoopExecute,Long routeDetailId, String followType) {

        HibernateStatelessResultAction<List<FactorData>> action = new AbstractHibernateStatelessResultAction<List<FactorData>>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                StringBuilder sqlBuilder = new StringBuilder();
                sqlBuilder.append("select patientId,stagesCode,stagesName,stagesRecordId ,stagesRecordCreateTime,teamChronicGroupId,dataSource from (");
                sqlBuilder.append("SELECT b.patient_id patientId,a.stages_code stagesCode, a.stages_name stagesName, a" +
                        ".stages_record_id stagesRecordId, a.create_time stagesRecordCreateTime ,a.team_chronic_group_id teamChronicGroupId,'1' dataSource");
                sqlBuilder.append(" FROM fus_group_chronic_record_stages_property a, fus_team_chronic_group_record b ");
                sqlBuilder.append(" WHERE a.team_chronic_group_id = b.team_chronic_group_id AND b.apply_status = '1' ");
                sqlBuilder.append("  AND a.stages_code in(:stagesCodeList) ");
                if (null != startTime) {
                    sqlBuilder.append("  and  a.create_time>:startTime ");
                }
                if (null != endTime) {
                    sqlBuilder.append("  and  a.create_time<:endTime ");
                }
                if (CommonUtils.isNotEmpty(patientIdList)) {
                    sqlBuilder.append(" and b.patient_id in(:patientIdList)");
                }
                sqlBuilder.append(") AS  m ");
                //循环执行机制 0 不执行 1 执行
                if (FollowTypeEnum.FUS_SPECIALIST.getType().equals(followType) && null != isLoopExecute && isLoopExecute == 1) {
                    sqlBuilder.append(" LEFT JOIN fus_factor_data_record f  ON f.patient_id = m.patientId   AND f.route_detail_id = :routeDetailId AND f.team_chronic_group_id = m.teamChronicGroupId WHERE f.id IS NULL  ");
                }
                Query query = ss.createSQLQuery(sqlBuilder.toString());
                query.setParameterList("stagesCodeList", factorIdList);
                if (null != startTime) {
                    query.setParameter("startTime", startTime);
                }
                if (null != endTime) {
                    query.setParameter("endTime", endTime);
                }
                if (CommonUtils.isNotEmpty(patientIdList)) {
                    query.setParameterList("patientIdList", patientIdList);
                }
                if (FollowTypeEnum.FUS_SPECIALIST.getType().equals(followType) && null != isLoopExecute && isLoopExecute == 1) {
                    query.setParameter("routeDetailId", routeDetailId);
                }
                query.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<Map> list = query.list();
                List<FactorData> voList = new ArrayList<>();
                if (CommonUtils.isNotEmpty(list)) {
                    for (Map map : list) {
                        voList.add(ConversionUtils.convert(map, FactorData.class));
                    }
                } else {
                    voList = new ArrayList<>();
                }
                setResult(voList);
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }
}
